//
//  PackageDetailsViewController.m
//  OrderSeat
//
//  Created by wangwei on 13-10-16.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "PackageDetailsViewController.h"
#import "ComfirmOrderNoSeatViewController.h"
#import "ShopHomeViewController.h"
#import "SeatViewController.h"
#import "OrderDetailViewController.h"
#import "LoginViewController.h"
#import "PackageDetailsCell.h"

#define ADD_DISH_TAG 1
#define REMOVE_DISH_TAG 2

@implementation PackageDetailsViewController

- (id)initWithShopId:(NSString *)shopId packageId:(NSString*)packageId
{
    self = [super initWithNibClass:[PackageDetailsViewController class]];
    if(self) {
        self.shopId    = shopId;
        self.packageId = packageId;
        _dataSource    = [[PackageDetailsDataSource alloc] initWithVC:self];
        [_dataSource fetchPackageDetails];
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
}

- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"套餐明细"];
    
    self.detailsTable.dataSource = self.dataSource;
    self.detailsTable.delegate = self.dataSource;
    
    [UIView drawBorders:@[_titleView, _detailsTable, _totalView]];
    
    NSString *packageName = [self.packageEntity objectForKey:@"taocan_name"];
    self.packageNameLabel.text = [NSString stringWithFormat:@" 套餐：%@",packageName];
    
    if (!_isNext) {
        [_btnSubmit setBackgroundNormal:@"btn_enable.png"];
        [_btnSubmit setTitleColorNormal:[UIColor grayColor]];
    }
    
    _theScrollview.hidden = YES;
}

- (void)leftButtonClick:(id)sender
{
    if (_orderSuccess) {
        [[AppDelegate sharedInstance] showTabBar:self.tabBarController];
        [self pushOrPopViewController:[ShopHomeViewController class]];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (IBAction)selectDishAction:(id)sender
{
    int count = [[self.packageEntity objectForKey:@"fenshu"] intValue];
    count = [sender tag] == REMOVE_DISH_TAG ? count-1 : count + 1;
    count = count < 0 ? 0 : count;
    
    NSString *str_count = [NSString stringWithFormat:@"%d",count];
    [self.packageEntity setObject:str_count forKey:@"fenshu"];
    
    self.countLabel.text = str_count;
    
    [self.detailsTable reloadData];
    
    [self totalCount:self.packageEntity];
}

- (void)totalCount:(NSDictionary *)dic
{
    int totalCount = 0;
    float totalMoney = 0;
    
    int count = [[dic objectForKey:@"fenshu"] intValue];
    float price = [[dic objectForKey:@"price"] floatValue];
    
    totalCount += count;
    totalMoney += price * count;
    
    _totalCountLabel.text = [NSString stringWithFormat:@"/%d份套餐",totalCount];
    _totalMoneyLabel.text = [NSString stringWithFormat:@"￥%.0f元",totalMoney];
    
    [_totalMoneyLabel autoWidthForSingleLine];
    [_totalCountLabel autoWidthForSingleLine];
    _totalCountLabel.left = _totalMoneyLabel.right;
}

- (void)submitOrder
{
    NSString *username = [AppSetting userName];
    NSString *shopId = _shopId;
    NSString *seat = _selectSeats;
    NSString *orderTime = S_EMPTY;
    NSString *zaowan = S_EMPTY;
    NSString *mobile = S_EMPTY;
    
    NSString *packageId = [_packageEntity objectForKey:@"id"];
    NSString *packCount = [_packageEntity objectForKey:@"fenshu"];
    NSString *url = [NSString stringWithFormat:API_PACKAGE_ORDER,username,shopId,packageId,packCount,orderTime,zaowan,mobile,seat,S_EMPTY,S_EMPTY];
    
    [_dataSource submitOrderWithURL:url];
}

- (IBAction)doneAction:(id)sender
{
    if (![AppDelegate checkLoginWithDelegate:self]) return;
    
    if (_isNext) {
        [AppDelegate showMessage:@"本餐厅暂时关闭在线点菜功能"];
        return;
    }
    
    if (_selectSeats) {
        [self submitOrder];
    }else {
        ComfirmOrderNoSeatViewController *comfirmVC = [[ComfirmOrderNoSeatViewController alloc] initWithShopId:_shopId];
        comfirmVC.packageEntity = self.packageEntity;
        [self.navigationController pushViewController:comfirmVC animated:YES];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    loginVC.backController = self;
    [self.navigationController pushViewController:loginVC animated:YES];
}

- (void)reLayoutSubviews
{
    _theScrollview.hidden = NO;
    
    [self.detailsTable reloadData];
    [self.detailsTable autoHeight];
    
    [UIView autoLayoutVertical:@[_titleView, _detailsTable, _totalView, _btnSubmit]];
    
    [self.theScrollview autoHeight];
}

#pragma 预定成功后，显示对话框
- (void)orderDidSuccess:(NSDictionary *)data
{
    self.orderSuccess = YES;
    self.orderId = [data objectForKey:@"order_id"];
    
    AlertWindowView *alert = [[AlertWindowView alloc] initWithMessage:@"恭喜您已预定成功" delegate:self buttonTitles:@[@"查看订单",@"去订座位"]];
    [self.view addSubview:alert];
    
    [alert showWindow];
}

- (void)alertWindow:(AlertWindowView *)alertWindow clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        OrderDetailViewController *orderVC = [[OrderDetailViewController alloc] initWithOrderId:_orderId andType:NewOrder];
        [self pushViewController:orderVC];
    }
    
    if (buttonIndex == 1) {
        ShopHomeViewController *vc = (ShopHomeViewController *)[self findControllerWithClass:[ShopHomeViewController class]];
        
        SeatViewController *seatVC = [[SeatViewController alloc] initWithShopId:_shopId];
        seatVC.data = vc.data;
        [self pushViewController:seatVC];
    }
}

@end

//====================================================================================
#pragma=========数据源实现==============================================================
//====================================================================================

@implementation PackageDetailsDataSource

#define CellHeight  36
#define FETCH_PACKAGE_TAG 1001
#define SUBMIT_ORDER_TAG 1002

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if (self) {
        self.viewController = viewController;
    }
    return self;
}

- (void)fetchPackageDetails
{
    [SVProgressHUD show];
    
    NSString *shopId = self.viewController.shopId;
    NSString *packageId = self.viewController.packageId;
    NSString *url = [NSString stringWithFormat:API_PACKAGE_DETAIL,shopId,packageId];
    
    [self get:url tag:FETCH_PACKAGE_TAG];
}

- (void)submitOrderWithURL:(NSString*)url
{
    [SVProgressHUD show];
    [self get:url tag:SUBMIT_ORDER_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    [SVProgressHUD dismiss];
    CLog(@"request: %@", request.responseString);
    
    NSDictionary *json = [request.responseData JSONValue];
    if ([[json objectForKey:@"error_code"] intValue] != 0) {
        return;
    }
    
    if (request.tag == FETCH_PACKAGE_TAG) {
        self.dishList = [json objectForKey:@"taocan"];
        [self.viewController reLayoutSubviews];
    }
    
    if (request.tag == SUBMIT_ORDER_TAG) {
        int state = [[json objectForKey:@"state"] intValue];
        
        if (state == 1) {
            [_viewController orderDidSuccess:json];
        }
        
        if (state == 2) {
            [AppDelegate showMessage:@"订单预定失败!"];
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dishList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 36;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellId = @"PackageDetailsCell";
    
    PackageDetailsCell *cell = [self.viewController createCellWithNib:CellId tableview:tableView];
    
    NSDictionary *dic = [self.dishList objectAtIndex:indexPath.row];
    [cell setContent:dic];
    
    return cell;
}

@end